import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/features/message/viewmodels/chat_viewmodel.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/models/message_shot.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/app/router/app_router.dart';

/// 聊天视图
/// 单聊页面，显示与某个用户的对话
class ChatView extends StatelessWidget {
  final String otherUserId;

  const ChatView({super.key, required this.otherUserId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ChatViewModel>.reactive(
      viewModelBuilder:
          () => ChatViewModel(
            getIt.get<AuthFocus>(),
            getIt.get<DialogLens>(),
            otherUserId,
          )..initialize(),
      onViewModelReady: (viewModel) {
        // 监听消息变化，自动滚动到底部
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [const Color(0xFFFFEBE6), const Color(0xFFFFA680)],
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: Column(
                children: [
                  // 顶部标题栏
                  _buildHeader(context, viewModel),
                  // 聊天消息列表
                  Expanded(
                    child:
                        viewModel.isBusy
                            ? const Center(child: CircularProgressIndicator())
                            : viewModel.currentUser == null
                            ? const Center(child: Text('Please login'))
                            : _buildMessageList(context, viewModel),
                  ),
                  // 底部输入栏
                  _buildInputBar(context, viewModel),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader(BuildContext context, ChatViewModel viewModel) {
    return Container(
      padding: EdgeInsets.only(left: 14.w, right: 14.w, bottom: 12.h),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.black.withOpacity(0.1), width: 1),
        ),
      ),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(
              Icons.chevron_left_rounded,
              size: 28.w,
              color: Colors.black87,
            ),
          ),
          SizedBox(width: 12.w),
          // 标题
          Expanded(
            child: Center(
              child: Text(
                'Information',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w800,
                      ).fontFamily,
                  color: Colors.black87,
                ),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 举报按钮
          GestureDetector(
            onTap: () {
              ComplainHelper.unveil(
                context,
                onComplain: (reason) async {
                  // 举报后删除所有消息并返回
                  await viewModel.deleteAllMessages();
                  // 显示举报成功提示
                  FlashNotifier.flashSuccess('Report submitted successfully');
                  if (context.mounted) {
                    Navigator.of(context).pop();
                  }
                },
              );
            },
            child: Container(
              width: 32.w,
              height: 32.w,
              padding: EdgeInsets.all(4.w),
              decoration: BoxDecoration(shape: BoxShape.circle),
              child: Image.asset('assets/images/report.png'),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息列表
  Widget _buildMessageList(BuildContext context, ChatViewModel viewModel) {
    if (viewModel.messages.isEmpty) {
      return Center(
        child: Text(
          'No messages yet',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.black.withOpacity(0.5),
          ),
        ),
      );
    }

    return ListView.builder(
      padding: EdgeInsets.all(14.w),
      reverse: false,
      itemCount: viewModel.messages.length,
      itemBuilder: (context, index) {
        final message = viewModel.messages[index];
        final isCurrentUser = message.senderId == viewModel.currentUser?.id;
        return _buildMessageItem(context, viewModel, message, isCurrentUser);
      },
    );
  }

  /// 构建消息项
  Widget _buildMessageItem(
    BuildContext context,
    ChatViewModel viewModel,
    MessageShot message,
    bool isCurrentUser,
  ) {
    final timeStr = DateFormat('HH:mm').format(message.timestamp);
    final user = isCurrentUser ? viewModel.currentUser : viewModel.otherUser;

    return Padding(
      padding: EdgeInsets.only(bottom: 14.h),
      child: Column(
        crossAxisAlignment:
            isCurrentUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: [
          // 消息气泡行（头像和气泡底部对齐）
          Row(
            mainAxisAlignment:
                isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              if (!isCurrentUser) ...[
                // 对方头像
                GestureDetector(
                  onTap: () async {
                    if (user == null) return;
                    // 检查是否是当前用户
                    final currentUser =
                        await getIt<AuthFocus>().getCurrentUser();
                    if (currentUser != null && currentUser.id == user.id) {
                      return; // 是自己的头像，不跳转
                    }
                    // 跳转到他人主页
                    if (context.mounted) {
                      await Navigator.of(context).pushNamed(
                        Routes.otherProfile,
                        arguments: {'userId': user.id},
                      );
                    }
                  },
                  child: SizedBox(
                    width: 46.w,
                    height: 46.w,
                    child: CircleAvatar(
                      radius: 23.r,
                      backgroundColor: Colors.white,
                      backgroundImage:
                          user?.avatar != null
                              ? AssetImage(user!.avatar!)
                              : null,
                      child:
                          user?.avatar == null
                              ? Icon(
                                Icons.person,
                                size: 23.w,
                                color: Colors.grey,
                              )
                              : null,
                    ),
                  ),
                ),
                SizedBox(width: 8.w),
              ],
              // 消息气泡
              Container(
                constraints: BoxConstraints(maxWidth: 230.w),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color:
                      isCurrentUser ? ColorConstants.accentColor : Colors.white,
                  borderRadius:
                      isCurrentUser
                          ? BorderRadius.only(
                            topLeft: Radius.circular(12.r),
                            topRight: Radius.circular(12.r),
                            bottomLeft: Radius.circular(12.r),
                            bottomRight: Radius.circular(0),
                          )
                          : BorderRadius.only(
                            topLeft: Radius.circular(12.r),
                            topRight: Radius.circular(12.r),
                            bottomLeft: Radius.circular(0),
                            bottomRight: Radius.circular(12.r),
                          ),
                ),
                child: Text(
                  message.type == MessageType.callFailed
                      ? 'Call failed'
                      : message.content,
                  style: TextStyle(
                    fontSize: 12.sp,
                    fontFamily:
                        GoogleFonts.notoSans(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    color: isCurrentUser ? Colors.white : Colors.black87,
                    height: 1.50,
                  ),
                ),
              ),
              if (isCurrentUser) ...[
                SizedBox(width: 8.w),
                // 当前用户头像
                SizedBox(
                  width: 46.w,
                  height: 46.w,
                  child: CircleAvatar(
                    radius: 23.r,
                    backgroundColor: Colors.white,
                    backgroundImage:
                        user?.avatar != null ? AssetImage(user!.avatar!) : null,
                    child:
                        user?.avatar == null
                            ? Icon(Icons.person, size: 23.w, color: Colors.grey)
                            : null,
                  ),
                ),
              ],
            ],
          ),
          // 时间戳单独一行
          Padding(
            padding: EdgeInsets.only(
              top: 4.h,
              left: isCurrentUser ? 0 : 54.w,
              right: isCurrentUser ? 54.w : 0,
            ),
            child: Text(
              timeStr,
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black.withOpacity(0.5),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建输入栏
  Widget _buildInputBar(BuildContext context, ChatViewModel viewModel) {
    return Container(
      padding: EdgeInsets.only(
        left: 14.w,
        right: 14.w,
        top: 12.h,
        bottom: 56.h,
      ),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.3),
        border: Border(
          top: BorderSide(color: Colors.black.withOpacity(0.1), width: 1),
        ),
      ),
      child: Row(
        children: [
          // 输入框
          Expanded(
            child: Container(
              height: 44.w,
              padding: EdgeInsets.only(left: 16.w, right: 8.w),
              decoration: BoxDecoration(
                color: const Color(0xFFFFB181),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: viewModel.messageController,
                      decoration: InputDecoration(
                        hintText: 'Send message',
                        hintStyle: TextStyle(
                          fontSize: 16.sp,
                          color: ColorConstants.greyColor,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.zero,
                      ),
                      style: TextStyle(fontSize: 16.sp, color: Colors.black),
                      maxLines: 1,
                      textInputAction: TextInputAction.send,
                      onSubmitted: (_) => viewModel.sendMessage(),
                    ),
                  ),
                  // 发送按钮（在输入框内）
                  GestureDetector(
                    onTap: () => viewModel.sendMessage(),
                    child: Container(
                      width: 32.w,
                      height: 32.w,
                      padding: EdgeInsets.all(4.w),
                      child: Image.asset(
                        'assets/images/send.png',
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 视频按钮
          GestureDetector(
            onTap: () {
              Navigator.of(context).pushNamed(
                Routes.videoCall,
                arguments: {'otherUserId': viewModel.otherUserId},
              );
            },
            child: Container(
              width: 44.w,
              height: 44.w,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.r),
                color: Colors.white,
              ),
              padding: EdgeInsets.all(10.w),
              child: Image.asset(
                'assets/images/video.png',
                fit: BoxFit.contain,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
